<?php

namespace app\admin\controller\user;

use addons\jiezicommon\service\Tools;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
//                ->whereIn('user.group_id', ['1', '2', '3'])
                ->with(['parent', 'group'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->cargo_value = fixNum($v['cargo_value']);
                $v->points = fixNum($v['points']);
                $v->activity_points = fixNum($v['activity_points']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $this->modelValidate = true;
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('groupName', \app\admin\model\UserGroup::where('id', $row['group_id'])->value('name'));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }



    /**
     * 修改平台积分
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit_points($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_points_log.php');
            $this->view->assign("typeList", (new \app\common\model\UserPointsLog())->getTypeList());
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $sn = Tools::getOrderSn();
//            $result = $row->allowField(true)->save($params);
            \app\common\model\User::points($params['type'], $sn, 0, $params['points'], $ids, $params['memo'], 0, $this->auth->id);
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



    /**
     * 修改活动积分
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit_activity_points($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_activity_points_log.php');
            $this->view->assign("typeList", (new \app\common\model\UserActivityPointsLog())->getTypeList());
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
//            $result = $row->allowField(true)->save($params);
            $sn = Tools::getOrderSn();
            \app\common\model\User::activity_points($params['type'], $sn, $params['points'], $ids, $params['memo'], 0, $this->auth->id);
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改货值
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit_cargo_value($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_cargo_value_log.php');
            $this->view->assign("typeList", (new \app\common\model\UserCargoValueLog)->getTypeList());
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
//            $result = $row->allowField(true)->save($params);
            $sn = Tools::getOrderSn();
            \app\common\model\User::cargo_value($params['type'], $sn, 0, $params['points'], $ids, $params['memo'], 0, $this->auth->id);
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改身份
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit_group($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::where('id', '<>', config('admin_group_id'))->column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('groupName', \app\admin\model\UserGroup::where('id', $row['group_id'])->value('name'));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['parent_id']){
            //获取他的上级树
            $parent_path_list = \addons\jiezicommon\service\Tools::getInstance()->getUserParentPath($params['parent_id']);
            if($parent_path_list){
                $parent_path_ids = array_column($parent_path_list, 'id');
                if(in_array($ids, $parent_path_ids)){
                    $this->error('该上级已经是你的下级成员了');
                }
            }
//            var_dump($parent_path_ids);die;
        }
        //新身份为一星时，父级必须为空
        if($params['group_id'] == 3){
            if($params['parent_id']){
                $this->error('一星用户不能有上级');
            }else{
                $params['parent_id'] = 0;
            }
        }
        //新身份为二星时，父级必须为一星
        if($params['group_id'] == 2){
            $parent = $this->model->get($params['parent_id']);
            if($parent && $parent['group_id'] != 3){
                $this->error('一星上级应该是二星');
            }
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
//            $sn = Tools::getOrderSn();
//            \app\common\model\User::cargo_value($params['type'], $sn, 0, $params['points'], $ids, $params['memo'], 0, $this->auth->id);
//            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改计算状态
     */
    public function edit_calc_auto_status($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->calc_auto_status = $row->calc_auto_status ? 0 : 1;
        $row->save();
        $this->success();
    }

    /**
     * 修改人工干预状态
     */
    public function edit_calc_manual_status($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->calc_manual_status = $row->calc_manual_status ? 0 : 1;
        $row->save();
        $this->success();
    }


    public function erweima($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        $hashids_obj = new \Hashids\Hashids(config('hashid_key'));
//        $en_code = $hashids_obj->encode($row->id, config('hashid_key'));
//        $en_code = \addons\jiezicommon\service\Tools::gen_code($ids);
        $en_code = $ids;
//        $en_code = "dafadsf";
//        $as = strToNum($en_code);
//        var_dump($en_code);die;
        /*
        $spread_url = request()->domain() . '/c/' . $en_code;
        $result = \Endroid\QrCode\Builder\Builder::create()
            ->data($spread_url)
            ->size(300)
            ->margin(10)
//                ->labelText('This is the label')
//            ->labelFont(new NotoSans(20))
//            ->labelAlignment(new LabelAlignmentCenter())
            ->build();
//            $result->saveToFile('./uploads/shop_erweims/123.png');
        */
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $scene = $arr['query'] ?? '';
        $page = $arr['path'] ?? '';
        $page = 'pages/login/reg';
        $mode = input('mode', 0);
        $width = input('width/d', 200);

        $scene = 'code=' . $en_code;
//            var_dump($scene);die;
        $response = $app->app_code->getUnlimit($scene, [
            'page' => $page,
            'check_path' => false,
            'width' => $width,
//                'env_version' => 'develop',
//                'env_version' => 'trial',
        ]);

        if (is_array($response)) {
            $this->error($response['errmsg']);
            die;
        }
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->getBody()->rewind();
//            $filename = $response->save('.' . $image, $filename);
            ob_start();
            // 输出图像
            $res = imagecreatefromstring($response->getBodyContents());
            imagepng($res);
            $content = ob_get_clean();
            imagedestroy($res);
            $row['erweima'] = 'data:image/png;base64,'. base64_encode($content);
//                $result = ['image' => base64_encode($content)];
//                return json($result);
//                return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        }
//        $row['spread_url'] = $spread_url;
//        $row['erweima'] = $result->getDataUri();
        $row['code'] = $en_code;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
}
